
import { _decorator, Component, Layers, Node, resources, Sprite, SpriteFrame, UITransform } from 'cc';
const { ccclass, property } = _decorator;
import { createUINode } from '../../Utils';
import { TileItem } from './TileItem';
import { DataManager } from '../../RunTime/DataManager';
import { ResourcesManager } from '../../RunTime/ResoucesManager';

export const TILE_WEIGHT = 55
export const TILE_HEIGHT = 55

@ccclass('TileManager')
export class TileManager extends Component {

  private defaultSpriteFrame: SpriteFrame;

  async init() {
    const spriteFramesMap = await this.loadTileRes()
    const DataManagerInstance = DataManager.getInstance()
    const {mapInfo} = DataManagerInstance

    const tiles = []

    for (let i = 0; i < mapInfo.length; i++) {
      const row = mapInfo[i]
      tiles[i] = []
      for (let j = 0; j < row.length; j++) {
        const item = row[j]
        if(item.src == null || item.type == null) continue

        const node = createUINode()
        const tile = node.addComponent(TileItem)
        const spriteFrame = spriteFramesMap[`tile (${item.src})`] || this.defaultSpriteFrame
        tile.init(spriteFrame, i, j, item.type)
        tiles[i][j] = tile
        node.setParent(this.node)

      }
    }
    DataManagerInstance.tiles = tiles


  }


  async loadTileRes() : Promise<Record<string, SpriteFrame>> {
    let result = {};
    const resourcesManager = ResourcesManager.getInstance()
    const spriteFrames = await resourcesManager.loadRes('texture/tile', SpriteFrame)

    this.defaultSpriteFrame = spriteFrames[0]
    for(let spriteFrame of spriteFrames){
      result[spriteFrame.name] = spriteFrame
    }

    return result

  }

}
